
package com.example.filetransfer.publicsource.connection;


import com.example.filetransfer.publicsource.Log;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Arrays;

public class NetBroadcastReceiver extends Thread {
    private static final String TAG = "NetBroadcastReceiver";

    public interface MessageListener {
        public void onNewMessageReceive(String message);
    }

    private DatagramSocket mClientRecevieSocket = null;
    private int mListenPort = -1;
    private static final int MAXREV = 255;
    // Control this thread running or exit.
    private volatile boolean mStop = false;
    private ThreadState mState = ThreadState.NOT_INIT;
    private MessageListener mListener;

    public NetBroadcastReceiver(int port) {
        mListenPort = port;
    }

    public void setMessageListener(MessageListener listener) {
        this.mListener = listener;
    }

    public ThreadState getThreadState() {
        return mState;
    }

    public void stopReceive() {
        mStop = true;
        mState = ThreadState.STOPING;
        if (mClientRecevieSocket != null) {
            mClientRecevieSocket.close();
        }
    }

    @Override
    public void run() {
        System.out.println("RUNNING HERE");
        try {
            mClientRecevieSocket = new DatagramSocket(mListenPort);
            DatagramPacket recvPacket = new DatagramPacket(new byte[MAXREV], MAXREV);
            mState = ThreadState.IDEL;
            while (!mStop) {
                mState = ThreadState.WORKING;
                mClientRecevieSocket.receive(recvPacket);
                byte[] receiveMsg = Arrays.copyOfRange(recvPacket.getData(),
                        recvPacket.getOffset(),
                        recvPacket.getOffset() + recvPacket.getLength());
                String receive = new String(receiveMsg);
                Log.d(TAG, "receive message=" + receive);
                if (mListener != null) {
                    mListener.onNewMessageReceive(receive);
                }
            }
        } catch (SocketException e) {
            System.err.println("socket exception");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (mClientRecevieSocket != null && !mClientRecevieSocket.isClosed()) {
                mClientRecevieSocket.close();
                mClientRecevieSocket = null;
            }
            mState = ThreadState.STOP;
        }
    }
}
